package com.sportizz.sport;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.sportizz.model.JustifiedTextView;
import com.sportizz.sport.row.Custom_set_row;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.LinearLayout.LayoutParams;

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
public class Setting_Act extends Activity {

	public static ActionBar actionBar;
	public static Button back_option;
	public DatabaseAdapter dataAdapter;
	public static ListView lv;

	private TextView txt_r_follow, empty, calendar_name,
			upcoming_name,title;

	public static ToggleButton check_cal;
	public static Button btn_info, nexthr_info, plus, minus;
	public Custom_set_row csr = null;
	public static TextView next_hr;

	public static AdView adview;

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		// startActivity(new Intent(this,First_sport_follow.class));
		getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

		LayoutInflater inflater = (LayoutInflater) getActionBar()
				.getThemedContext().getSystemService(LAYOUT_INFLATER_SERVICE);
		View customActionBarView = inflater.inflate(
				R.layout.setting_action_bar, null);

		actionBar = getActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.actionbar_bg));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
				| ActionBar.DISPLAY_SHOW_TITLE);
		actionBar.setCustomView(customActionBarView,
				new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.MATCH_PARENT));

		win.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
				WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);

		// ...but notify us that it happened.
		win.setFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
				WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

		setContentView(R.layout.setting_layout);

		dataAdapter = new DatabaseAdapter(this);

		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		// imm.hideSoftInputFromWindow(search_text.getWindowToken(), 0);

		lv = (ListView) findViewById(R.id.listView_sett);

		txt_r_follow = (TextView) findViewById(R.id.text_r_follow);
		next_hr = (TextView) findViewById(R.id.next_hr);

		calendar_name = (TextView) findViewById(R.id.calendar_name);
		upcoming_name = (TextView) findViewById(R.id.upcoming_name);

		plus = (Button) findViewById(R.id.plus);
		minus = (Button) findViewById(R.id.minus);
		check_cal = (ToggleButton) findViewById(R.id.ch_add_cal);
		btn_info = (Button) findViewById(R.id.btn_info);

		nexthr_info = (Button) findViewById(R.id.nexthr_info);

		empty = (TextView) findViewById(R.id.empty_text_set);
		
		Typeface title_font = Typeface.createFromAsset(this.getAssets(),
				"hel57.ttf");
		
		empty.setTypeface(title_font);
		
		adview = (AdView) findViewById(R.id.adView2);

		// dataAdapter.close();
		dataAdapter.open();

		
		
		back_option = (Button) customActionBarView
				.findViewById(R.id.btn_back_setting);

		title = (TextView) customActionBarView
		.findViewById(R.id.actionBar_title_setting);
		
		title.setTypeface(title_font);
		
		back_option.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dataAdapter.close();
				finish();
			}
		});

		Log.d("suraj", "Setting ");

		int f_count = dataAdapter.total_follow();

		Log.v("suraj", "TOTAL FOLLOW = " + f_count);

		final ArrayList<String> champ_follow = new ArrayList<String>();
		final ArrayList<String> player_follow = new ArrayList<String>();

		final ListView listView = getListView();

		lv.setDividerHeight(0);

//		if (MainActivity.interstitial.isReady()) {
//			MainActivity.interstitial.show();
//		} else {
//			Log.d("suraj_", "Interstitial ad was not ready to be shown.");
//		}

		Typeface tf = Typeface.createFromAsset(this.getAssets(),
				"Hel67medium.ttf");

		// txt_check_calendar.setTypeface(tf);
		// txt_follow_pack.setTypeface(tf);
		txt_r_follow.setTypeface(tf);

		// unlimited_name.setTypeface(tf);
		calendar_name.setTypeface(tf);
		upcoming_name.setTypeface(tf);

		MainActivity.pur_status = MainActivity.preferences_purchase.getString(
				"purchase_status", null);

		int pur_foll = StartActivity.limited_follow.getInt("max_follow", 3);


		
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				adview.setVisibility(View.VISIBLE);
				AdRequest adRequest = new AdRequest();
				adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
				adview.loadAd(adRequest);
			}
		});		
			
			
		dataAdapter.open();
		String upcoming_value = dataAdapter.getupcomingValue();

		Log.e("suraj_", "Upcoming Value = " + upcoming_value);

		if (upcoming_value.equals("24")) {
			next_hr.setText("24 HRS");
		} else if (upcoming_value.equals("10")) {
			next_hr.setText("10 HRS");
		} else if (upcoming_value.equals("4")) {
			next_hr.setText("4 HRS");
		}

		String cal = dataAdapter.getcalValue();
		if (cal.equals("Y")) {
			check_cal.setChecked(true);//Text("24 HRS");
		} else if (cal.equals("N")) {
			check_cal.setChecked(false);
		}
		
		dataAdapter.close();
		final List<follow_player> follow_items = new ArrayList<follow_player>();

		csr = new Custom_set_row(this, R.layout.setting_row, follow_items);

		listView.setAdapter(csr);

		AsyncTask<Void, Void, Void> wait = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				dataAdapter.close();
				csr.notifyDataSetChanged();
			}

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
			}

			@Override
			protected Void doInBackground(Void... params) {
				dataAdapter.close();
				dataAdapter.open();
				Cursor follow_p_list = null;
				follow_p_list = dataAdapter.getfollowerlist();
//				startManagingCursor(follow_p_list);

				Cursor follow_c_list = null;
				follow_c_list = dataAdapter.getchamplist();
//				startManagingCursor(follow_c_list);

				// int count=0;
				if (follow_p_list != null) {

					while (!follow_p_list.isAfterLast()) {
						player_follow.add(follow_p_list.getString(follow_p_list
								.getColumnIndex("player_id")));
						follow_p_list.moveToNext();
					}
					Log.v("suraj", "Player count = " + player_follow);
				}

				if (follow_c_list != null) {
					while (!follow_c_list.isAfterLast()) {
						champ_follow.add(follow_c_list.getString(follow_c_list
								.getColumnIndex("player_id")));
						//
						follow_c_list.moveToNext();
					}
					Log.v("suraj", "champ count = " + champ_follow);

				}

//				follow_p_list.close();
//				follow_c_list.close();
				player_follow.addAll(champ_follow);

				Log.e("suraj", "Combine data = " + player_follow);

				if (player_follow.size() == 0) {

					Thread t = new Thread(new Runnable() {

						@Override
						public void run() {

							runOnUiThread(new Runnable() {
								public void run() {
									MainActivity.playerAll.clear();

									// empty.setVisibility(View.VISIBLE);
									// empty.setText("You are currently not following any Team, Player or Sporting Event");
									lv.setEmptyView(empty);
								}
							});

						}
					});
					t.start();
				} else {
					for (int j = 0; j < player_follow.size(); j++) {

						Bitmap b2 = null;

						Cursor getsett_follow = null;

						Log.v("suraj", "Player = " + player_follow.get(j));

						getsett_follow = dataAdapter
								.getAllData_follow(player_follow.get(j));

						startManagingCursor(getsett_follow);

						String player_code = getsett_follow
								.getString(getsett_follow
										.getColumnIndex("player_id"));

						String name = getsett_follow.getString(getsett_follow
								.getColumnIndex("player_name"));

						String team = getsett_follow.getString(getsett_follow
								.getColumnIndex("is_team"));

						String sport_code = getsett_follow
								.getString(getsett_follow
										.getColumnIndex("sport_code"));

						String sport = getsett_follow.getString(getsett_follow
								.getColumnIndex("sport"));

						String national = getsett_follow
								.getString(getsett_follow
										.getColumnIndex("national"));

						Log.d("suraj", "msg = " + national);

						if (team.equals("Y")) {
							if (MainActivity.tablet == false) {

								if (national.equals(player_code)) {
									Log.d("suraj",
											"player code some as national");
									b2 = download_Image(""
											+ StartActivity.get_img_location
											+ "phone/" + sport_code
											+ "/" + player_code + ".png",
											sport_code, team);
								} else {
									Log.d("suraj",
											"player code NOT some as national");
									b2 = download_Image(""
											+ StartActivity.get_img_location
											+ "phone/country/"
											+ national + ".png", sport_code,
											team);
								}

							} else {

								if (national == player_code) {
									b2 = download_Image(""
											+ StartActivity.get_img_location
											+ "pad/" + sport + "/"
											+ player_code + "@2x.png",
											sport_code, team);
								} else {
									b2 = download_Image(""
											+ StartActivity.get_img_location
											+ "pad/country/"
											+ national + "@2x.png", sport_code,
											team);
								}
							}
						} else if (team.equals("N")) {

							if (MainActivity.tablet == false) {
								b2 = download_Image(""
										+ StartActivity.get_img_location
										+ "phone/country/"
										+ national + ".png", sport_code, team);
							} else {

								b2 = download_Image(""
										+ StartActivity.get_img_location
										+ "pad/country/" + national
										+ "@2x.png", sport_code, team);
							}

						} else if (team.equals("A")) {
							if (MainActivity.tablet == false) {
								b2 = download_Image(""
										+ StartActivity.get_img_location
										+ "phone/CS/" + player_code
										+ ".png", sport_code, team);
							} else {
								b2 = download_Image(""
										+ StartActivity.get_img_location
										+ "pad/CS/" + player_code
										+ "@2x.png", sport_code, team);
							}
						}

						Log.v("suraj", "BITMAP in Follow_ADD = " + b2);

						follow_items
								.add(new follow_player(b2, name, player_code,
										sport, national, sport_code, team));
						getsett_follow.close();

					}
				}
				return null;
			}
		};
		wait.execute();

		csr.notifyDataSetChanged();
		listView.invalidate();

		SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
				listView,
				new SwipeDismissListViewTouchListener.OnDismissCallback() {
					@Override
					public void onDismiss(ListView listView,
							int[] reverseSortedPositions) {
						for (int position : reverseSortedPositions) {

							Log.v("suraj",
									"Remove ="
											+ follow_items.get(position)
													.getName()
											+ " Id is :"
											+ follow_items.get(position)
													.getpcode());

							if (follow_items.get(position).getteam().toString()
									.equals("Y")
									|| follow_items.get(position).getteam()
											.toString().equals("N")) {
								Utils.getJSONString("http://sportizza.com/interface/ios_unfollow.php?dev_id="
										+ MainActivity.device_id
										+ "&player_unfollow="
										+ follow_items.get(position).getpcode()
										+ "&cs_unfollow=-1");
							} else if (follow_items.get(position).getteam()
									.toString().equals("A")) {
								Utils.getJSONString("http://sportizza.com/interface/ios_unfollow.php?dev_id="
										+ MainActivity.device_id
										+ "&player_unfollow=-1&cs_unfollow="
										+ follow_items.get(position).getpcode()
										+ "");
							}
							// dataAdapter.close();

							 dataAdapter.open();
							int row_del = dataAdapter
									.unfollow_player(follow_items.get(position)
											.getpcode().toString());

							if (row_del != 0) {
								follow_items.remove(position);

								if (StartActivity.foll_count != 0) {
									StartActivity.foll_count--;
								} else {
									StartActivity.foll_count = 0;
								}
								SharedPreferences.Editor editor = StartActivity.follow_count
										.edit();
								editor.putInt("follow_count",
										StartActivity.foll_count);
								editor.commit();

								csr.notifyDataSetChanged();
								// findViewById(R.id.progressBar1)
								// .setVisibility(View.GONE);
							} else {
								SharedPreferences.Editor editor = StartActivity.follow_count
										.edit();
								editor.putInt("follow_count", 0);
								editor.commit();
							}
							 dataAdapter.close();

						}

						if (csr.getCount() == 0) {
							MainActivity.playerAll.clear();

							lv.setEmptyView(empty);
						}

					}
				});

		lv.setOnTouchListener(touchListener);
		lv.setOnScrollListener(touchListener.makeScrollListener());

		check_cal
				.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked) {
							dataAdapter.open();
							
							Log.d("suraj","Value ="+dataAdapter.getcalValue());
							String ca=dataAdapter.getcalValue();
							
							if (ca.equals("N")) {
								dataAdapter.updatecalValue("Y", "N");
							} 
							
							Log.d("suraj","Value ="+dataAdapter.getcalValue());
							dataAdapter.close();
						} else {

							 dataAdapter.open();
							 
							Log.d("suraj","Value ="+dataAdapter.getcalValue());
							
							 String ca=dataAdapter.getcalValue();
							if (dataAdapter.getcalValue().equals("Y")) {
								dataAdapter.updatecalValue("N", "Y");
							} 
							Log.d("suraj","Value ="+dataAdapter.getcalValue());
							dataAdapter.close();
						}
					}
				});

		btn_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				String msg = "Whenever you go to the 'I follow' screen, Add Follows to calendar will put all events on 'I follow' screen on your calendar. Switch it off to disable this feature.";

				initiatePopupWindow(msg);

			}
		});

		nexthr_info.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				String msg = "click on button to set upcoming schedule for 24, 36 or 72 hours. Go to Upcoming tab to view schedule.";

				initiatePopupWindow(msg);

			}
		});

		plus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				String number = next_hr.getText().toString();

				String[] hour = number.split(" ");

				int next_hour = Integer.parseInt(hour[0]);

				dataAdapter.open();

				if (next_hour == 24) {
					dataAdapter.updateupcomingValue("36", "24");
					next_hr.setText("36 HRS");
				} else if (next_hour == 36) {
					dataAdapter.updateupcomingValue("72", "36");
					next_hr.setText("72 HRS");
				} else if (next_hour == 72) {
					dataAdapter.updateupcomingValue("24", "72");
					next_hr.setText("24 HRS");
				}
				dataAdapter.close();
			}
		});

		minus.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				String number = next_hr.getText().toString();

				String[] hour = number.split(" ");

				Log.d("suarj", "hour=" + hour[0]);

				int next_hour = Integer.parseInt(hour[0]);

				dataAdapter.open();

				if (next_hour == 72) {
					dataAdapter.updateupcomingValue("36", "72");
					next_hr.setText("36 HRS");
				} else if (next_hour == 36) {
					dataAdapter.updateupcomingValue("24", "36");
					next_hr.setText("24 HRS");
				} else if (next_hour == 24) {
					dataAdapter.updateupcomingValue("72", "24");
					next_hr.setText("72 HRS");
				}
				dataAdapter.close();

			}
		});

	}

	protected void initiatePopupWindow(String msg) {
		try {
			LayoutInflater inflater = (LayoutInflater) Setting_Act.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View layout = inflater.inflate(R.layout.popup_window,
					(ViewGroup) findViewById(R.id.popup_element));
			final PopupWindow pwindo = new PopupWindow(layout, LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT, true);
			pwindo.showAtLocation(layout, Gravity.CENTER, 0, 0);
			JustifiedTextView txt_msg = (JustifiedTextView) layout
					.findViewById(R.id.txtView);

			// String htmlText = " %s ";

			txt_msg.setText(msg);
			// txt_msg.setTextColor(Color.BLACK);

			// txt_msg.loadData(String.format(htmlText, msg), "text/html",
			// "utf-8");
			// txt_msg.setTextColor(Color.BLACK);

			Button btnClosePopup = (Button) layout
					.findViewById(R.id.btn_close_popup);
			btnClosePopup.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {

					pwindo.dismiss();

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	private Bitmap download_Image(String url, String sport_code, String team) {

		Bitmap bm = null;

		try {
			URL aURL = new URL(url);
			URLConnection conn = aURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			BufferedInputStream bis = new BufferedInputStream(is);
			bm = BitmapFactory.decodeStream(bis);
			bis.close();
			is.close();
		} catch (IOException e) {
			Log.e("Hub", "Error getting the image from server : ");
			try
			{
			InputStream is1 = null;
					is1 = Setting_Act.this.getResources()
							.getAssets()
							.open("new_sports/"
									+ sport_code + ".png");
			bm = BitmapFactory.decodeStream(is1);
			}catch (Exception e1) {
				InputStream is1 = null;
				try {
					is1 = Setting_Act.this.getResources()
							.getAssets()
							.open("new_sports/GAM.png");
				bm = BitmapFactory.decodeStream(is1);
				} catch (IOException e2) {
				}
			}
		}
		return bm;
	}

	private ListView getListView() {
		// TODO Auto-generated method stub
		return lv;
	}

}
